package com.settlement.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.settlement.system.common.annotation.AppPreventDuplicateSubmit;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.model.dto.FileInfo;
import com.settlement.system.model.entity.*;
import com.settlement.system.model.form.RechargeForm;
import com.settlement.system.model.form.SysFlowMarketForm;
import com.settlement.system.model.form.SysLazyToolUserForm;
import com.settlement.system.model.form.UserRunLogForm;
import com.settlement.system.model.vo.LazyUserVo;
import com.settlement.system.model.vo.NetAutoGroup;
import com.settlement.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端控制类
 */
@Tag(name = "移动端控制类")
@RestController
@RequestMapping("/api/v1/app")
@RequiredArgsConstructor
public class APPController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${oss.minio.endpoint}")
    private String endpoint;

    @Value("${oss.minio.bucket-name}")
    private String bucketName;

    private final RedisTemplate redisTemplate;

    private final SysLazyToolUserService sysLazyToolUserService;

    private final SysFlowMarketService sysFlowMarketService;

    private final SysUserFlowService sysUserFlowService;

    private final OssService ossService;

    private final SysFeedbackService sysFeedbackService;

    private final SysDemandService sysDemandService;

    private final WxPayService wxPayService;

    private final SysPayOrderService sysPayOrderService;

    private final SysAppVersionService appVersionService;

    private final SysLazyUserNoticeService sysLazyUserNoticeService;

    private final SysUserRunLogService sysUserRunLogService;

    private final SysAppErrorLogService sysAppErrorLogService;

    private final SysWechatService sysWechatService;

    @Operation(summary = "获取手机验证码")
    @GetMapping("/getCode/{mobile}")
    @SuppressWarnings("unchecked")
    public Result<?> getCode(@Parameter(description = "手机号") @PathVariable String mobile) {
        try {
            Object code = redisTemplate.opsForValue().get(SystemConstants.MOBILE_CODE_CACHE_PREFIX + mobile);
            if (code != null) {
                return Result.failed("已经获取过验证码，请在5分钟内不要重复获取");
            }
            StringBuilder newCode = new StringBuilder();
            // 随机生成4位数字的字符串
            for (int i = 0; i < 4; i++) {
                int randomNum = (int) (Math.random() * 10);
                newCode.append(randomNum);
            }
            // 将验证码存入redis
            redisTemplate.opsForValue().set(SystemConstants.MOBILE_CODE_CACHE_PREFIX + mobile, newCode.toString(), 5, TimeUnit.MINUTES);
            return Result.success(newCode);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "注册懒人秘籍用户")
    @PostMapping("/register")
    @AppPreventDuplicateSubmit
    public Result<?> registerSysLazyToolUser(HttpServletRequest request, @RequestBody @Valid SysLazyToolUserForm sysLazyToolUserForm) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            boolean success = sysLazyToolUserService.registerSysLazyToolUser(sysLazyToolUserForm);
            return Result.judge(success);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "测试重复提交")
    @PostMapping("/testDuplicateSubmit")
    @AppPreventDuplicateSubmit
    public Result<?> testDuplicateSubmit() {
        try {
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "通过注册邮箱找回密码")
    @PostMapping("/forgetPwd")
    @AppPreventDuplicateSubmit(expire = 5) // 5秒内禁止重复提交
    public Result<?> forgetPwd(HttpServletRequest request, @RequestBody LazyUserVo lazyUserVo) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            // 通过注册的手机号码和邮箱找回密码，通过邮件发送密码返回给用户
            sysLazyToolUserService.findPwd(lazyUserVo.getMobile(), lazyUserVo.getEmail());
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "修改密码")
    @GetMapping("/updatePwd/{newPwd}/{deviceId}")
    @AppPreventDuplicateSubmit
    public Result<?> updatePwd(HttpServletRequest request, @PathVariable String newPwd, @PathVariable String deviceId) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            // 通过注册的手机号码和邮箱找回密码，通过邮件发送密码返回给用户
            sysLazyToolUserService.updatePwd(userId, newPwd, deviceId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "登录懒人秘籍用户")
    @PostMapping("/login")
    @AppPreventDuplicateSubmit
    public Result<?> loginSysLazyToolUser(HttpServletRequest request, @RequestBody @Valid SysLazyToolUserForm sysLazyToolUserForm) {
        try {
            Result<?> resultObj = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(resultObj)) {
                return resultObj;
            }
            SysLazyToolUser result = sysLazyToolUserService.loginSysLazyToolUser(sysLazyToolUserForm);
            LazyUserVo vo = new LazyUserVo();
            vo.setMobile(result.getMobile());
            vo.setEmail(result.getEmail());
            vo.setMember(result.getMember());
            vo.setMemberLevel(result.getMemberLevel());
            vo.setId(result.getId());
            vo.setMemberExpireDate(result.getMemberExpireDate());
            vo.setExperienceDate(result.getExperienceDate());
            return Result.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "体验会员")
    @PostMapping("/experience")
    @AppPreventDuplicateSubmit
    public Result<?> experience(HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            // userId 即是 用户ID
            sysLazyToolUserService.experience(userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "充值会员")
    @PostMapping("/recharge")
    @AppPreventDuplicateSubmit
    public Result<?> recharge(HttpServletRequest request, @RequestBody @Valid RechargeForm rechargeForm) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            rechargeForm.setId(Long.parseLong(userId));
            sysLazyToolUserService.recharge(rechargeForm);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "检查是否可以运行流程")
    @GetMapping("/checkCanRunFlow")
    @AppPreventDuplicateSubmit
    public Result<?> checkCanRunFlow(HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            String deviceId = request.getParameter("deviceId");
            sysLazyToolUserService.checkCanRunFlow(userId, deviceId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "保存或者更新流程市场")
    @PostMapping("/saveFlow")
    @AppPreventDuplicateSubmit
    public Result<?> saveFlow(@RequestParam String type, @RequestParam String flowName, @Parameter(description = "表单文件对象") @RequestParam(value = "file") MultipartFile file) {
        try {
            // 获取文件大小，单位是kb
            double fileSize = file.getSize() / 1024.0;
            FileInfo fileInfo = ossService.uploadFile(file);
            SysFlowMarketForm sysFlowMarketForm = new SysFlowMarketForm();
            sysFlowMarketForm.setType(type);
            sysFlowMarketForm.setFlowName(flowName);
            sysFlowMarketForm.setFileName(fileInfo.getName());
            sysFlowMarketForm.setFilePath(fileInfo.getUrl());
            sysFlowMarketForm.setFileSize(new BigDecimal(fileSize).setScale(2, RoundingMode.HALF_UP));
            boolean result = sysFlowMarketService.saveSysFlowMarket(sysFlowMarketForm);
            return Result.judge(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "发布到脚本市场")
    @PostMapping("/publish")
    @AppPreventDuplicateSubmit
    public Result<?> publish(@RequestParam String type, @RequestParam Long flowId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            boolean publishResult = sysFlowMarketService.publish(flowId, type, null);
            return Result.judge(publishResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户获取脚本")
    @PostMapping("/linkFlow")
    @AppPreventDuplicateSubmit
    public Result<?> linkFlow(@RequestParam(value = "flowId") Long flowId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            sysUserFlowService.linkFlow(flowId, Long.parseLong(userId));
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "运行时通过脚本ID下载最新脚本")
    @PostMapping("/downloadFlow")
    @AppPreventDuplicateSubmit
    public Result<?> downloadFlow(@RequestParam(value = "flowId") Long flowId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String urlLink = sysFlowMarketService.downloadFlow(flowId);
            return Result.success(urlLink);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }


    @Operation(summary = "用户反馈")
    @PostMapping("/feeBack")
    @AppPreventDuplicateSubmit
    public Result<?> feeBack(@RequestParam String content, @Parameter(description = "表单文件对象") @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String mobile = request.getParameter("appId");
            SysFeedback sysFeedback = new SysFeedback();
            if (file != null) {
                FileInfo fileInfo = ossService.uploadFile(file);
                sysFeedback.setFileName(fileInfo.getName());
                sysFeedback.setFilePath(fileInfo.getUrl());
            }
            sysFeedback.setContent(content);
            sysFeedback.setMobile(mobile);
            sysFeedbackService.saveSysFeedback(sysFeedback);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户需求")
    @PostMapping("/demand")
    @AppPreventDuplicateSubmit
    public Result<?> demand(@RequestParam String content, @Parameter(description = "表单文件对象") @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String mobile = request.getParameter("appId");
            SysDemand sysDemand = new SysDemand();
            if (file != null) {
                FileInfo fileInfo = ossService.uploadFile(file);
                sysDemand.setFileName(fileInfo.getName());
                sysDemand.setFilePath(fileInfo.getUrl());
            }
            sysDemand.setContent(content);
            sysDemand.setMobile(mobile);
            sysDemandService.saveSysDemand(sysDemand);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }


    @Operation(summary = "用户已读需求")
    @PostMapping("/readDemand")
    @AppPreventDuplicateSubmit
    public Result<?> readDemand(@RequestParam Long demandId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysDemandService.readDemand(demandId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    /**
     * pageNumber 默认是1，代表是第一页，每次下拉就传加1过来查下一页
     */
    @Operation(summary = "获取用户需求")
    @GetMapping("/demandList")
    @AppPreventDuplicateSubmit
    public Result<?> demandList(@RequestParam(required = false) Integer pageNumber, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            if (pageNumber == null) {
                // 默认第一页
                pageNumber = 1;
            }
            String mobile = request.getParameter("appId");
            List<SysDemand> sysDemands = sysDemandService.demandList(mobile, pageNumber);
            return Result.success(sysDemands);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户已读反馈")
    @PostMapping("/readFeeBack")
    @AppPreventDuplicateSubmit
    public Result<?> readFeeBack(@RequestParam Long feeBackId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysFeedbackService.readFeeBack(feeBackId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    /**
     * pageNumber 默认是1，代表是第一页，每次下拉就传加1过来查下一页
     */
    @Operation(summary = "获取用户反馈")
    @GetMapping("/feeBackList")
    @AppPreventDuplicateSubmit
    public Result<?> feeBackList(@RequestParam(required = false) Integer pageNumber, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            if (pageNumber == null) {
                // 默认第一页
                pageNumber = 1;
            }
            String mobile = request.getParameter("appId");
            List<SysFeedback> sysFeedbacks = sysFeedbackService.feeBackList(mobile, pageNumber);
            return Result.success(sysFeedbacks);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "获取流程市场分类查询脚本列表(用户端接口)")
    @GetMapping("/flowList")
    @AppPreventDuplicateSubmit
    public Result<?> flowList(HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String mobile = request.getParameter("appId");
            List<NetAutoGroup> flowMarkets = sysFlowMarketService.getUserFlowList(mobile);
            return Result.success(flowMarkets);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "获取所有脚本列表(管理端接口)")
    @GetMapping("/getAllFlowList")
    @AppPreventDuplicateSubmit
    public Result<?> getAllFlowList() {
        try {
            List<NetAutoGroup> flowMarkets = sysFlowMarketService.getAllFlowList();
            return Result.success(flowMarkets);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 微信支付
     *
     * @param data 参数
     * @return 支付信息
     */
    @RequestMapping("/nativePay")
    @Operation(summary = "微信支付")
    @AppPreventDuplicateSubmit
    public Result<?> nativePay(@RequestParam Map<String, String> data) {
        Result<?> result;
        try {
            String userId = data.get("userId");
            String body = data.get("body");
            String money = data.get("money");
            if (StringUtils.isBlank(body)) {
                result = Result.failed("body is null");
                return result;
            }
            if (StringUtils.isBlank(money)) {
                result = Result.failed("money is null");
                return result;
            }
            Map<String, Object> map = wxPayService.nativePay(Long.parseLong(userId), body, money);
            result = Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.failed("支付系统繁忙，请稍后再试");
        }
        return result;
    }

    @Operation(summary = "查找订单状态是否支付完成")
    @PostMapping("/checkOrderStatus")
    @AppPreventDuplicateSubmit(expire = 1)
    public Result<?> checkOrderStatus(@RequestParam String orderNo, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            boolean orderFinish = sysPayOrderService.checkOrderFinish(orderNo);
            return Result.judge(orderFinish);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "推送一条通知到用户")
    @PostMapping("/saveNotice")
    @AppPreventDuplicateSubmit
    public Result<?> saveNotice(@RequestBody SysLazyUserNotice sysLazyUserNotice, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            sysLazyUserNotice.setUserId(Long.parseLong(userId));
            sysLazyUserNoticeService.saveSysLazyUserNotice(sysLazyUserNotice);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "获取用户未读通知")
    @PostMapping("/userNotice")
    @AppPreventDuplicateSubmit
    public Result<?> userNotice(HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String userId = request.getParameter("appId");
            return Result.success(sysLazyUserNoticeService.countUserUnRead(Long.parseLong(userId)));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户已读通知")
    @PostMapping("/readNotice")
    @AppPreventDuplicateSubmit
    public Result<?> readNotice(@RequestParam Long noticeId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysLazyUserNoticeService.readNotice(noticeId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "检查版本")
    @GetMapping("/checkVersion")
    @AppPreventDuplicateSubmit
    public Result<?> checkVersion(@RequestParam int version, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String filePath = appVersionService.checkVersion(version);
            filePath = endpoint + File.separator + bucketName + File.separator + filePath;
            return Result.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户运行日志")
    @PostMapping("/userLog")
    @AppPreventDuplicateSubmit
    public Result<?> userLog(@RequestBody UserRunLogForm userRunLogForm, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysUserRunLogService.saveSysUserRunLog(userRunLogForm);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    /**
     * pageNumber 默认是1，代表是第一页，每次下拉就传加1过来查下一页
     */
    @Operation(summary = "获取用户运行日志")
    @GetMapping("/userLogList")
    @AppPreventDuplicateSubmit
    public Result<?> userLogList(@RequestParam(required = false) Integer pageNumber, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            if (pageNumber == null) {
                // 默认第一页
                pageNumber = 1;
            }
            String mobile = request.getParameter("appId");
            List<SysUserRunLog> sysUserRunLogs = sysUserRunLogService.getUserRunLogs(mobile, pageNumber);
            return Result.success(sysUserRunLogs);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "用户运行日志已读")
    @GetMapping("/userLogRead")
    @AppPreventDuplicateSubmit
    public Result<?> userLogRead(@RequestParam Long logId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysUserRunLogService.read(logId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "删除用户运行日志")
    @GetMapping("/deleteUserLog")
    @AppPreventDuplicateSubmit
    public Result<?> deleteUserLog(@RequestParam Long logId, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            sysUserRunLogService.deleteSysUserRunLog(logId.toString());
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "根据脚本名称下载最新脚本")
    @GetMapping("/downloadFileByName")
    @AppPreventDuplicateSubmit(expire = 1)
    public Result<?> downloadFileByName(@RequestParam String fileName, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String filePath = sysFlowMarketService.getFilePathByName(fileName);
            return Result.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "手机端APP运行失败信息")
    @PostMapping("/appRunError")
    @AppPreventDuplicateSubmit
    public Result<?> appRunError(@RequestParam String appName, @RequestParam String message, @Parameter(description = "表单文件对象") @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            String mobile = request.getParameter("appId");
            SysAppErrorLog appErrorLog = new SysAppErrorLog();
            if (file != null) {
                FileInfo fileInfo = ossService.uploadFile(file);
                appErrorLog.setFilePath(fileInfo.getName());
            }
            appErrorLog.setMobile(mobile);
            appErrorLog.setMessage(message);
            appErrorLog.setAppName(appName);
            sysAppErrorLogService.getBaseMapper().insert(appErrorLog);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }

    @Operation(summary = "获取管理员微信")
    @GetMapping("/userWechat")
    @AppPreventDuplicateSubmit(expire = 2)
    public Result<?> userWechat(HttpServletRequest request) {
        try {
            Result<?> result = RequestUtils.resolveMobileToken(request, secret, sysLazyToolUserService);
            if (!Result.isSuccess(result)) {
                return result;
            }
            List<SysWechat> list = sysWechatService.list(new LambdaQueryWrapper<SysWechat>().eq(SysWechat::getUseStatus, 1));
            // 打乱顺序
            Collections.shuffle(list);
            SysWechat sysWechat = list.get(0);
            sysWechat.setFilePath(endpoint + File.separator + bucketName + File.separator + sysWechat.getFilePath());
            return Result.success(sysWechat);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(e.getMessage());
        }
    }
}
